# -*- coding: utf-8 -*-
"""
cron:  23 7 * * *
new Env('网易云音乐-增强版');
"""
import requests
import os
from io import StringIO
try:
    from notify import send  # 青龙通知模块
except ImportError:
    print("⚠️ 未找到青龙通知模块，使用本地打印")
    def send(title, content):
        print(f"【{title}】\n{content}")
class NeteaseMusicEnhanced:
    def __init__(self, cookie):
        self.sio = StringIO()
        self.cookie = cookie
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Referer': 'https://music.163.com/',
            'Cookie': cookie,
            'Accept': 'application/json'
        }
    def sign_task(self, task_type):
        """执行签到任务并增强响应处理"""
        url = f"https://music.163.com/api/point/dailyTask?type={task_type}"
        try:
            resp = requests.get(url, headers=self.headers, timeout=10)
            data = resp.json()
            
            if data.get('code') == 200:
                # 手机端(type=0)特殊处理：显示msg（如果存在）
                if task_type == 0 and 'msg' in data:
                    return f"🎉 获得 {data.get('point', 0)} 云贝 | 提示: {data['msg']}"
                else:
                    return f"🎉 获得 {data.get('point', 0)} 云贝"
            elif data.get('code') in [301, -2]:
                return "✅ 今日已签到"
            elif data.get('code') == 400:
                return "⚠️ 请求参数错误"
            elif data.get('code') == 401:
                return "🔒 需要重新登录"
            else:
                return f"❌ 错误: code={data.get('code')}, msg={data.get('message', '无')}"
        except Exception as e:
            return f"❗ 请求异常: {str(e)}"
    def run(self):
        """主运行逻辑"""
        self.sio.write("🎵 网易云音乐签到结果 🎵\n\n")
        
        if not self.cookie:
            self.sio.write("❌ 未配置Cookie\n")
            return self.sio.getvalue()
        
        # 手机端签到（type=0）
        self.sio.write(f"📱 手机端: {self.sign_task(0)}\n")
        # PC端签到（type=1）
        self.sio.write(f"💻 PC端: {self.sign_task(1)}\n")
        
        return self.sio.getvalue()
if __name__ == '__main__':
    # 从青龙环境变量获取Cookie
    cookie = os.getenv('MUSIC163', '').strip()
    if not cookie:
        print("❌ 请设置环境变量 MUSIC163")
        send("网易云音乐错误", "未配置Cookie")
        sys.exit(1)
    # 执行签到
    result = NeteaseMusicEnhanced(cookie).run()
    print(result)
    send("网易云音乐签到", result)